<?php
			
	/* SVN FILE: $Id: edit.php 8 2011-03-13 08:32:38Z michele.andreoletti@gmail.com $ */
	
	/**
	 * Project Name : arcadia
	 *
	 * @author $Author: michele.andreoletti@gmail.com $
	 * @version $Revision: 8 $
	 * @lastrevision $Date: 2011-03-13 08:32:38 +0000 (Sun, 13 Mar 2011) $
	 * @filesource $URL: http://arcadia.googlecode.com/svn/trunk/sysop/edit.php $
	 */

	require_once '../include/functions.php';
	require_once '../include/const.inc.php';
	require_once '../include/auth.inc.php';
	require_once '../include/conn.inc.php';

	fnOnly4Sysop();

	$sScript = fnCurrentScript();
	$sSCRIPT_ROOT_PATH = (fnIsScriptInRoot() ? '.' : '..'); // Variabile utilizzata in template.php
	
	fnGetValueFromGET(array('sUsername', 'sType'));
	if (!isset($sType)) $sType='user'; // se eseguo lo script senza passare il parametro sType, viene impostato di default == 'user'
	
	switch ($sType) {
		
		case "group":
			$sLabel = "Gruppi";
			break;
		
		default:
			$sType = "user";
			$sLabel = "Utenti";
			break;
	
	}

	$aRow = fnCheckUsername($sUsername, $sType);

	if (!empty($aRow)) {
		$sAPP_NAME = '&nbsp;';
		$sLEFT_NAV_IMG = "contact-new.png";
		$sHeaderTitle = $sTableTitle = "$sSUITE_NAME &raquo; ".$aRow['sUsername'];

	} else {
		fnUpdateLog('USERNAME NOT FOUND', 0, '','E');
		die('Username not found');

	} 

	$iEnabled = $aRow['iEnabled'];	
	$aEnableUserAction = array('1'=>'Sospendi', '0'=>'Attiva');
	$aAction = array('1'=>'Disable', '0'=>'Enable');
	$aManageSelectOptionValues = array ('0', '-1', '1', '2', '3', '9');

	$html .= "<div id='sysop'>";
	
	$html .= "<a href='index.php?sType=$sType'>&laquo; Ritorna a Gestione $sLabel</a>";
	
	$html .= "<table><tbody>";
	
	$html .= "<tr>	<th>username</th>
					<td><strong>".$aRow['sUsername']."</strong>".
						
							($sType=='user' ?
							
							"<div>
								<span id='EnabledUser' class='trigger' enabled='$iEnabled'><span id='EnabledUserAction'>".$aEnableUserAction[$iEnabled]."</span> Utente</span>
								<span id='TrashUser' class='trigger'><span id='TrashUserAction'>Elimina</span> Utente</span>
							</div>" :
							
							"<div>
								<span id='TrashUser' class='trash-trigger'><span id='TrashUserAction'>Elimina</span> Gruppo</span>
							</div>").
							
					"</td></tr>";
			
	if ($sType=='user') {
		$html .= "<tr>	<th>ultimo accesso</th>
						<td>".fnGetLastLogin($aRow['sUsername'])."
						<div class='enabled-user-info' style='display:".(empty($aRow['iEnabled']) ? '' : 'none').";'>Utente Sospeso</div>
						</td></tr>";
		$html .= "<tr>
					<th>Password</th>
					<td>
						<div class='edit' style='width: 250px'>***</div>
						<span id='ChangePassword' class='trigger'>Modifica Password</span>
					</td></tr>";
	
		$html .= "<tr>
					<th>Sysop</th>
					<td>
						<input type='checkbox' name='iSysop' ".($aRow['iSysop']==1 ? "checked" : "")." ".($aRow['sUsername']==fnReadSessionValue('sUsername') ? "disabled": "")." class='toggable' sUsername='".$aRow['sUsername']."' sType='".$aRow['sType']."'>
						Autorizza <strong>".$aRow['sUsername']."</strong> ad amministrare <strong>".$sSUITE_NAME."</strong>
					</td></tr>";	
	}
			
	$html .= "<tr>
				<th>Descrizione</th>
				<td>
					<span class='edit' id='sDisplayname'>".(empty($aRow['sDisplayname']) ? "&nbsp;" : $aRow['sDisplayname'])."</span>
					<span class='edit-trigger'>Modifica</span>
					<span class='cancel-trigger' style='display:none;'><a href='#'>Annulla</a></span>
				</td></tr>";
		
	if ($sType=='user') {	
		$html .= "<tr>
					<th>Email</th>
					<td>
						<span class='edit' id='sEmail'>".(empty($aRow['sEmail']) ? "&nbsp;" : $aRow['sEmail'])."</span>
						<span class='edit-trigger'>Modifica</span>
						<span class='cancel-trigger' style='display:none;'><a href='#'>Annulla</a></span>
					</td></tr>";
	}
	
	$html .= "<tr>
				<th>Permessi</th>
				<td>
					<div class='edit'>".fnHtmlGetAccessLvl($aRow['sUsername'], $aRow['sType'])."</div>
				</td></tr>";
		
	if ($sType=='user') {	
		$html .= "<tr>
					<th>Gruppi</th>
					<td>
						<div class='edit'>".fnHtmlGetAssociatedGroups($aRow['sUsername'])."</div>
						<span id='Add' class='trigger'>Aggiungi</span>
					</td></tr>";
	}

	else if ($sType=='group') {	
		$html .= "<tr>
					<th>Membri</th>
					<td>
						<div class='edit'>".fnHtmlGetMembersUsers($aRow['sUsername'])."</div>
						<span id='Add' class='trigger'>Aggiungi</span>
					</td></tr>";
	}

	$html .= "</tbody></table>";
	
	$html .= "</div>";
	
	$html .= "<div class='dialog' id='EnableUserDialog' title='Attiva Utente'>";
	$html .= "	<p>Attivare <strong><span id='EnableUserDialogText'>".$aRow['sUsername']."</span></strong>?</p>";
	$html .= "</div>";

	$html .= "<div class='dialog' id='DisableUserDialog' title='Sospendi Utente'>";
	$html .= "	<p>Sospendere <strong><span id='EnableUserDialogText'>".$aRow['sUsername']."</span></strong>?</p>
				<p>L'utente non verrà cancellato e potrà essere nuovamente attivato in futuro.</p>";
	$html .= "</div>";
	
	$html .= "<div class='dialog' id='TrashUserDialog' title='Elimina'>";
	$html .= "	<p>Sei sicuro di voler eliminare <strong><span id='TrashUserDialogText'>".$aRow['sUsername']."</span></strong>?</p>
				<p>Questa operazione non potrà essere annullata.</p>";
	$html .= "</div>";
	
	$html .= "<div class='dialog' id='RemoveDialog' title='Rimuovi'>";
	$html .= "	<p>Rimuovere <strong><span id='RemoveDialogText'></span></strong>?</p>";
	$html .= "</div>";	

	$html .= "	
		<div class='dialog' id='ManageDialog' title='Permessi'>
			<p class='validateTips'></p>
			<form>
				<fieldset>
					<select name='manage-select' id='manage-select' class='text ui-widget-content ui-corner-all'>";
						foreach ($aManageSelectOptionValues as $iOptionValue) {
							$html .= "<option value='$iOptionValue'>".fnDisplayAccessLvl($iOptionValue, 'text')."</option>";
						}			
	$html .= "		</select>
				</fieldset>
			</form>
		</div>";
	
	$html .= "	
		<div class='dialog' id='AddDialog' title='Aggiungi'>
			<p class='validateTips'></p>
			<form>
				<fieldset>
					<select name='AddSelect' id='AddSelect' class='text ui-widget-content ui-corner-all'>
					</select>
				</fieldset>
			</form>
		</div>";
	
	$html .= "	
		<div class='dialog' id='ChangePasswordDialog' title='Modifica Password'>
			<p class='validateTips'></p>
			<form>
				<fieldset>
					<label for='sPassword'>Nuova Password</label>
					<input type='password' name='sPassword' id='sPassword' class='text ui-widget-content ui-corner-all' />
					<label for='sPassword2'>Conferma Nuova Password</label>
					<input type='password' name='sPassword2' id='sPassword2' value='' class='text ui-widget-content ui-corner-all' />
				</fieldset>
			</form>
		</div>";
	
	$html .= "<div class='dialog' id='ChangedPasswordDialog' title='Modifica Password'>";
	$html .= "	<p>Password modificata con successo.</p>";
	$html .= "</div>";	
	
	$sHeadContent = <<<EOT
		<script type="text/javascript" src="../include/jquery.jeditable.mini.js"></script>
		
		<script type="text/javascript" src="include/user.js"></script>
		
		<script type="text/javascript" charset="utf-8">
			
			function fnToggle (oObj) {
				$.getJSON("actions.php", {"sUsername": oObj.attr("sUsername"), "sType": oObj.attr("sType"), "sAction": "update", "sField": oObj.attr("name"), "sValue": (oObj.attr("checked") ? 1 : 0) }, function (json) {
					if (oObj.attr("checked")) {
						oObj.attr("checked", false);
					} else {
						oObj.attr("checked", true);
					}
				})
			}

			function fnChangePassword (sUser, oPassword) {
				$.getJSON("actions.php", { "sUsername": sUser, "sType": "user", "sAction": "password", "sValue": oPassword.val() }, function(json) {
					$('#ChangedPasswordDialog').dialog('open');
				} );
			};
			
			function fnTrashUser (sUsername, sType) {
				$.getJSON("actions.php", { "sUsername": sUsername, "sType": sType, "sAction": "trash" }, function(json) {
					fnRedirectTo('index.php?sType='+sType);
				} );
			};

			/* Rimuove un utente da un gruppo */
			function fnRemove (sUsername, sType, sItem) {
				$.getJSON("actions.php", { "sUsername": sUsername, "sType": sType, "sAction": "remove", "sItem": sItem }, function(json) {
					$('#' + sItem).fadeOut(function() {
    					// Animation complete.
  						if ($('.sItems:visible').length == 0) { $('#EmptyItems').show(); }
  					});
				} );
			};
			
			function fnAdd (sUsername, sType, sItem) {
				$.getJSON("actions.php", { "sUsername": sUsername, "sType": sType, "sAction": "users_groups_lnk", "sItem": sItem }, function(json) {
					$('#' + sItem).show();
  					fnHighLight($('#' + sItem).children('.DisplayApp'));
  					if ($('.sItems:visible').length > 0) { $('#EmptyItems').hide(); }
				} );
			};	

			function fnManage (sUsername, sType, sApp, iAccessLvl) {
					$.getJSON("actions.php", { "sUsername": sUsername, "sType": sType, "sAction": "users_access_lvl", "sApp": sApp, "iAccessLvl": iAccessLvl }, function(json) {
						$('#' + sApp).children('img').attr('iAccessLvl', iAccessLvl);
						$('#' + sApp).children('.DisplayAccessLvl').html("&nbsp;" + json[0].sHtml + "&nbsp;");
						fnHighLight($('#' + sApp).children('.DisplayAccessLvl'));
					} );
				};

			function fnEnabledUser (sUser, sValue) {
				$.getJSON("actions.php", { "sUsername": sUser, "sType": "$sType", "sAction": "update", "sField": "iEnabled", "sValue": sValue } );
				$('.enabled-user-info').toggle();
				$('#EnabledUser').unbind('click');
				if (sValue == 1) {
					$('#EnabledUserAction').text('$aEnableUserAction[1]');
					$('#EnabledUser').click(function() {
						$('#DisableUserDialog').dialog('open');
						return false;
					});
				} else {
					$('#EnabledUserAction').text('$aEnableUserAction[0]');
					$('#EnabledUser').click(function() {
						$('#EnableUserDialog').dialog('open');
						return false;
					});
				}
			};
			
			$(document).ready(function() {
			
				oPassword = $("#sPassword"),
					oPassword2 = $("#sPassword2"),
					oAllFields = $([]).add(oPassword).add(oPassword2),
					oTips = $(".validateTips");
												
				$('#EnabledUser').click(function() {
					$('#$aAction[$iEnabled]UserDialog').dialog('open');
						return false;
				});
				
				$('#EnableUserDialog').dialog({
					autoOpen: false,
					resizable: false,
					modal: true,
					buttons: {
						'Attiva': function() {
							fnEnabledUser('$sUsername', 1);
							$(this).dialog('close');
							},
						'Annulla': function() {
							$(this).dialog('close');
						}
					}
				});	
								
				$('#DisableUserDialog').dialog({
					autoOpen: false,
					resizable: false,
					modal: true,
					buttons: {
						'Sospendi': function() {
							fnEnabledUser('$sUsername', 0);
							$(this).dialog('close');
							},
						'Annulla': function() {
							$(this).dialog('close');
						}
					}
				});	
																				
				$('#TrashUser').click(function() {
					$('#TrashUserDialog').dialog('open');
						return false;
				});
						
				$('#TrashUserDialog').dialog({
					autoOpen: false,
					resizable: false,
					modal: true,
					buttons: {
						'Elimina': function() {
					 		fnTrashUser('$sUsername', '$sType');
							$(this).dialog('close');
						},
						'Annulla': function() {
							$(this).dialog('close');
						}
					}
				});	
				
				$('.Remove').click(function() {
					$('#RemoveDialog').attr('sUsername', $(this).attr('sUsername'));
					$('#RemoveDialogText').text($(this).attr('sUsername'));
					$('#RemoveDialog').dialog('open');
						return false;
				});
						
				$('#RemoveDialog').dialog({
					autoOpen: false,
					resizable: false,
					modal: true,
					buttons: {
						'Rimuovi': function() {
					 		fnRemove('$sUsername', '$sType', $(this).attr('sUsername'));
							$(this).dialog('close');
						},
						'Annulla': function() {
							$(this).dialog('close');
						}
					}
				});	

				$('.Manage').click(function() {
					$('#ManageDialog').attr('sApp', $(this).attr('sApp'));
					oTips.html('Selezionare il livello di accesso all\'applicazione <strong><span id=\'ManageDialogAppName\'></span></strong> per <strong>$sUsername</strong>:');
					$('#ManageDialogAppName').text($(this).attr('sAPP_NAME'));
					$('#manage-select').val($(this).attr('iAccessLvl'));
					$('#ManageDialog').dialog('open');
						return false;
				});
						
				$('#ManageDialog').dialog({
					autoOpen: false,
					resizable: false,
					modal: true,
					buttons: {
						'Modifica': function() {
					 		fnManage('$sUsername', '$sType', $(this).attr('sApp'), $('#manage-select').val());
							$(this).dialog('close');
						},
						'Annulla': function() {
							$(this).dialog('close');
						}
					},
					close: function() {
						oAllFields.val('').removeClass('ui-state-error');
					}
				});	
								
				$('#Add').click(function() {
					$.getJSON("select.php", { "sUsername": '$sUsername', "sType": "$sType", "sAction": "users_groups_lnk" }, function(j) {
						var options = '';
						for (var i = 0; i < j.length; i++) {
							options += "<option value='" + j[i].sItem + "'>" + j[i].sDisplayname + "</option>";
						} 
						$("#AddSelect").html(options);
						$('#AddDialog').dialog('open');
					} );
						return false;	
				});
				
				$('#AddDialog').dialog({
					autoOpen: false,
					resizable: false,
					modal: true,
					buttons: {
						'Aggiungi': function() {
							if ($("#AddSelect").val()!='') {
						 		fnAdd('$sUsername', '$sType', $("#AddSelect").val());
								$(this).dialog('close');
							} else {
								updateTips('Seleziona una opzione dal menu.');
							}
						},
						'Annulla': function() {
							$(this).dialog('close');
						}
					}
				});	
				
				$('#ChangePassword').click(function() {
					oTips.html('Digitare le nuova password per l\'utente <strong>$sUsername</strong>:');
					$('#ChangePasswordDialog').dialog('open');
						return false;
				});

				$('#ChangePasswordDialog').dialog({
					autoOpen: false,
					resizable: false,
					modal: true,
					buttons: {
						'Modifica': function() {
							var bValid = true;
							oAllFields.removeClass('ui-state-error');
							bValid = bValid && checkLength(oPassword,"Password",5,16);
							bValid = bValid && checkLength(oPassword2,"Password",5,16);

							bValid = bValid && checkRegexp(oPassword,/^([0-9a-zA-Z])+$/,"La Password può contenere solo i seguenti caratteri: a-z, 0-9.");
							bValid = bValid && checkRegexp(oPassword2,/^([0-9a-zA-Z])+$/,"La Password può contenere solo i seguenti caratteri: a-z, 0-9.");
							
							bValid = bValid && checkCompare(oPassword, oPassword2)
							
							if (bValid) {
								fnChangePassword('$sUsername', oPassword);
								$(this).dialog('close');	
							}
						},
						'Annulla': function() {
							$(this).dialog('close');
						}
					},
					close: function() {
						oAllFields.val('').removeClass('ui-state-error');
					}
				});
				
				$('#ChangedPasswordDialog').dialog({
					autoOpen: false,
					resizable: false,
					modal: true,
					buttons: {
						'Ok': function() {
							$(this).dialog('close');
						}
					}
				});
								
				$(".toggable").click(function() {
					fnToggle($(this));
						return false;
				});
				
				$(".edit").editable('jeditable.php', {
					placeholder : "&nbsp;",
		        	id : 'sField',
        			name : 'sValue',
					event : "edit",
					width : "300px",
		        	submitdata : {sUsername: "$sUsername", sType: "$sType"},
		        	callback : function(value, settings) {
		        		$('.cancel-trigger').hide();
		        		$('.edit-trigger').show();
				        fnHighLight($(this));
    				},
 		        	onreset : function() {
		        		$('.cancel-trigger').hide();
		        		$('.edit-trigger').show();
    				}
				});
			
				$(".edit-trigger").bind("click", function() {
					$(this).next('.cancel-trigger').show();
					$(this).hide();
				    $(this).prev('span').trigger("edit");
				   	return false;
				});
				     
			});

		</script>

EOT;
	
	require_once('../themes/'.$sTHEME.'/template.php');
	die();
	
?><html><body bgcolor="#fff"></body></html>



<?php 

	function fnHtmlGetAssociatedGroups ($sUsername) {
		
		$html = '';
		$sQuery = fnQueryGetAssociatedGroups($sUsername);
		$aAssociatedGroups = fnGetDataFromQuery($sQuery, 'fnQueryGetAssociatedGroups()');
		$sQuery = fnQueryGetAllGroups();
		$aAllGroups= fnGetDataFromQuery($sQuery);
		$html = fnHtmlGroupsMembersInfo($aAllGroups, $aAssociatedGroups, 'group');
		
		return $html;		
	}

	function fnHtmlGetMembersUsers ($sGroup) {

		$html = '';
		$sQuery = fnQueryGetMembersUsers($sGroup);
		$aMembersUsers = fnGetDataFromQuery($sQuery, 'fnQueryGetMembersUsers()');
		$sQuery = fnQueryGetAllUsers();
		$aAllUsers = fnGetDataFromQuery($sQuery);
		$html = fnHtmlGroupsMembersInfo($aAllUsers, $aMembersUsers, 'user');
		
		return $html;
	}		

	function fnHtmlGroupsMembersInfo ($aData, $aAssociated, $sType) {
		
		$html = '';
		
		if ($sType=='user') {
			$sItem = 'sUser';
		
		} else if ($sType=='group') {
			$sItem = 'sGroup';
		
		}
		
		$sEmptyItemsDisplay = '';
		
		foreach ($aData as $aRow) {
			$sDisplay = 'none';
			foreach ($aAssociated as $aEntry) {
				if ($aEntry[$sItem] == $aRow[$sItem])
					$sDisplay = '';	
					$sEmptyItemsDisplay = 'none';	
			}
			$html .= "<div class='sItems' style='display: $sDisplay;' id='".$aRow[$sItem]."'><span class='DisplayApp'>".$aRow[$sItem]."</span>";
			if (!empty($aRow['sDisplayname'])) {
				$html .= "&nbsp;(".$aRow['sDisplayname'].")";
			}		
			$html .= "&nbsp;<img sUsername='".$aRow[$sItem]."' sType='$sType' class='Remove' src='../themes/common/images/icn_trash.gif'>";
			$html .= "</div>";						
		}
		
		$html .= "<div id='EmptyItems' style='display: $sEmptyItemsDisplay;';>&nbsp;</div>";	
		
		return $html;
	}


	function fnHtmlGetAccessLvl ($sUsername, $sType) {
		
		$html = '';
		
		$aAppsAccessLvl = fnGetDataFromQuery(fnQueryGetAppsAccessLvl($sUsername, $sType), 'fnQueryGetAppsAccessLvl()');

		global $aSUITE;
		foreach ($aSUITE as $sApp => $aValues) {
			$iAccessLvl = 0;
			$html .= "<div class='sApps' id='".$sApp."'><strong>".$aValues['sAPP_NAME']."</strong>";
			foreach ($aAppsAccessLvl as $aAppAccessLvl) {
				if ($sApp == $aAppAccessLvl['sApp']) {
					$iAccessLvl = $aAppAccessLvl['iAccessLvl'];
				}
			}
			$html .= "&nbsp;&nbsp;&raquo;&nbsp;<span class='DisplayAccessLvl'>".fnDisplayAccessLvl($iAccessLvl, 'html')."</span>";
			$html .= "&nbsp;<img sApp='$sApp' sAPP_NAME='".$aValues['sAPP_NAME']."' iAccessLvl='$iAccessLvl' class='Manage' src='../themes/common/images/icn_pencil.gif'>";
			$html .= "</div>";						
		}
		
		return $html;			
	}

?>